package com.qimei.onerice.servlet;

import com.qimei.onerice.entity.Order;
import com.qimei.onerice.entity.OrderDetail;
import com.qimei.onerice.service.OrderDetailService;
import com.qimei.onerice.service.OrderService;
import com.qimei.onerice.service.impl.OrderDetailServiceImpl;
import com.qimei.onerice.service.impl.OrderServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/orderDetail")
public class OrderDetailServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String action = request.getParameter("action");
		String orderDetailId = request.getParameter("orderDetailId");

		OrderDetailService orderDetailService = new OrderDetailServiceImpl();
		OrderService orderService = new OrderServiceImpl();

		if ("delete".equals(action)) {
			// 删除订单明细
			OrderDetail orderDetail = orderDetailService.getOrderDetailById(Integer.parseInt(orderDetailId));
			// 首先更新订单总价
			Order newOrder = orderService.getOrderById(orderDetail.getOrderId());
			newOrder.setTotalAmount(newOrder.getTotalAmount() - orderDetail.getSubtotal());
			orderService.updateOrder(newOrder);
			// 最后删除订单明细
			orderDetailService.deleteOrderDetail(Integer.parseInt(orderDetailId));
		}
		request.getRequestDispatcher("/view/cart.jsp").forward(request, response);
	}
}
